/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */

package com.ecarx.systemui.plugin.utils;

import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.UserHandle;
import android.widget.Toast;

import androidx.annotation.StringRes;

import com.ecarx.systemui.plugin.PluginContext;
import com.ecarx.systemui.plugin.common.CommonUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

public class AppUtils {

    private static final String TAG = "AppUtilsTag";

    public final static String LAUNCHER_COMPONENT = "ecarx.launcher3/.Launcher";
    public final static String LAUNCHER_COMPONENT_PSD = "ecarx.launcher3/ecarx.psd.LauncherForPSD";

    //public final static String SETTINGS_COMPONENT1 = "ecarx.settings/.activitys.CarSettingActivity";
    public final static String SETTINGS_COMPONENT2 = "ecarx.settings/.activitys.home.CarSettingsActivity";

    public final static String CLIMATE_COMPONENT = "com.ecarx.car.ecarxhvac/.MainActivity";

    public final static String MEDIA_COMPONENT = "com.ecarx.multimedia/.main.MainActivity";

    public final static String GALLERY_OPEN_ACTION = "ecarx.intent.action.ECARX_GALLERY_OPEN";

    public final static String GALLERY_USB_URI = "ecarx://gallery.com/usb";

    public final static String NAVIGATION_COMPONENT = "com.ecarx.navi/.MainActivity";

    public final static String NAVIGATION_COMPONENT_PSD = "com.ecarx.navi/.PsdMainActivity";


    // app panel
    public final static String ACTION_APP_PANEL = "ecarx.intent.action.keyevent_app_panel";

    //按压Home
    public final static String ACTION_HOME = "ecarx.intent.action.keyevent_home";

    public static final String PACKAGE_HVAC = "com.ecarx.car.ecarxhvac";
    public static final String ACTION_SEAT_ADJUST = "ecarx.hvac.action.SEAT_ADJUST_PANEL";

    public final static String PACKAGE_AVM = "com.ecarx.parking";
    public static final String ACTION_AVM = "ecarx.intent.action.AVM";

    public final static String PACKAGE_APA = "com.ecarx.apa";
    public static final String ACTION_APA = "ecarx.intent.action.APA";


    public static void startSeatAdjust(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent(ACTION_SEAT_ADJUST);
            intent.setPackage(PACKAGE_HVAC);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            doStartActivityAsUser(context, intent, isCSD);
            LogUtils.d(TAG, "startSeatAdjust");
        } catch (Exception e) {
            LogUtils.e(TAG, "startSettings error :" + e.getMessage());
        }
    }

    /**
     * @param context    Context
     * @param isAppPanel isAppPanel
     * @param isCSD
     */
    public static void startLauncher(Context context, boolean isAppPanel, boolean isCSD) {
        // 启动launcher3
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            if (isCSD) {
                intent.setComponent(ComponentName.unflattenFromString(LAUNCHER_COMPONENT));
                intent.addCategory(Intent.CATEGORY_HOME);
            } else {
                intent.setComponent(ComponentName.unflattenFromString(LAUNCHER_COMPONENT_PSD));
                intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
            }

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle bundle = new Bundle();
            bundle.putBoolean("toAppPane", isAppPanel);
            intent.putExtras(bundle);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startLauncher error :" + e.getMessage());
        }
    }

    public static void startNavigation(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            if (isCSD) {
                intent.setComponent(ComponentName.unflattenFromString(NAVIGATION_COMPONENT));
            } else {
                intent.setComponent(ComponentName.unflattenFromString(NAVIGATION_COMPONENT_PSD));
            }
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startNavigation error :" + e.getMessage());
        }
    }

    public static void startSettings(Context context, boolean isCSD) {
        // Settings
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setComponent(ComponentName.unflattenFromString(SETTINGS_COMPONENT2));
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startSettings error :" + e.getMessage());
        }
    }


    public static void startEnergy(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent();
            intent.setAction("ecarx.settings.action.ENERGY");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("type", "chargeOrDischargeAuto");
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startEnergy error :" + e.getMessage());
        }
    }


    public static void startMedia(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setComponent(ComponentName.unflattenFromString(MEDIA_COMPONENT));
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startMedia error :" + e.getMessage());
        }
    }


    public static void startGallery(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent(GALLERY_OPEN_ACTION);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.parse(GALLERY_USB_URI));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startMedia error :" + e.getMessage());
        }
    }


    @SuppressWarnings("unused")
    public static void startAvm(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setPackage(PACKAGE_AVM);
            intent.setAction(ACTION_AVM);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startAvm error :" + e.getMessage());
        }
    }

    public static void startApa(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setPackage(PACKAGE_APA);
            intent.setAction(ACTION_APA);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startAvm error :" + e.getMessage());
        }
    }

    public static void startClimate(Context context, boolean isCSD) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setComponent(ComponentName.unflattenFromString(CLIMATE_COMPONENT));
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            doStartActivityAsUser(context, intent, isCSD);
        } catch (Exception e) {
            LogUtils.e(TAG, "startClimate error :" + e.getMessage());
        }
    }

    public static void registerReceiver(Context context,
                                        BroadcastReceiver broadcastReceiver,
                                        IntentFilter intentFilter) {
        doRegisterBroadCast(context, broadcastReceiver, intentFilter);
    }


    public static void bindService(Context context, Intent intentService,
                                   ServiceConnection connection) {
        doBindService(context, intentService, connection);
    }

    @SuppressWarnings("ConstantConditions")
    private static void doBindService(Context context, Intent intentService,
                                      ServiceConnection connection) {

        UserHandle userHandle = getUserHandle();
        if (userHandle == null) {
            LogUtils.e(TAG, "getUserHandle is null , so return");
            return;
        }
        try {
            Class<?> c = Class.forName("android.content.Context");
            Method get = c.getMethod("bindServiceAsUser", Intent.class,
                    ServiceConnection.class, int.class, UserHandle.class);
            boolean isBind = (boolean) get.invoke(context,
                    intentService,
                    connection,
                    Context.BIND_AUTO_CREATE,
                    userHandle
            );
            LogUtils.d(TAG, "doBindService isBind :" + isBind);
        } catch (ClassNotFoundException | NoSuchMethodException |
                 InvocationTargetException | IllegalAccessException e) {
            LogUtils.e(TAG, "doBindService error :" + e.getMessage());
        }

    }

    @SuppressWarnings("JavaReflectionMemberAccess")
    private static void doRegisterBroadCast(Context context, BroadcastReceiver broadcastReceiver,
                                            IntentFilter intentFilter) {
        try {
            UserHandle userHandle = getUserHandle();
            if (userHandle == null) {
                LogUtils.e(TAG, "getUserHandle is null , so return");
                return;
            }
            Class<?> c = Class.forName("android.content.Context");
            Method get = c.getMethod("registerReceiverAsUser", BroadcastReceiver.class,
                    UserHandle.class, IntentFilter.class, String.class, Handler.class);
            get.invoke(context,
                    broadcastReceiver,
                    userHandle,
                    intentFilter,
                    null,
                    null
            );
            LogUtils.d(TAG, "doRegisterBroadCast OK");
        } catch (Exception e) {
            LogUtils.e(TAG, "doRegisterBroadCast error :" + e.getMessage());
        }
    }

    @SuppressWarnings("JavaReflectionMemberAccess")
    private static void doStartActivityAsUser(Context context, Intent intent, boolean isCSD) {
        try {
            ActivityOptions options = ActivityOptions.makeBasic();
            int displayId = CommonUtils.getDisplayId(context, isCSD);
            options.setLaunchDisplayId(displayId);
            LogUtils.i(TAG, "doStartActivityAsUser -> displayId =" + displayId + " intent:" + intent);
            context.startActivityAsUser(intent, options.toBundle(), UserHandle.CURRENT);
        } catch (Exception e) {
            LogUtils.e(TAG, "doStartActivityAsUser error :" + e.getMessage());
        }
    }


    public static void sendHomeAppPanelBroadcast(Context context, boolean appPanel, boolean animate) {
        UserHandle userHandle = getUserHandle();
        if (userHandle == null) {
            LogUtils.e(TAG, "getUserHandle is null , so return");
            return;
        }
        boolean isLaunchExist = isLauncherExist(context);
        Intent intent = new Intent();
        intent.putExtra("animate", animate);
        if (isLaunchExist) {
            if (appPanel) {
                intent.setAction(ACTION_APP_PANEL);
            } else {
                intent.setAction(ACTION_HOME);
            }
            context.sendBroadcastAsUser(intent, userHandle);
        } else {
            LogUtils.e(TAG, "sendHomeAppPanelBroadcast launcher is not exist");
        }
    }

    @SuppressWarnings({"ConstantConditions",
            "JavaReflectionMemberAccess"})
    private static UserHandle getUserHandle() {
        try {
            Class<?> activityManager = Class.forName("android.app.ActivityManager");
            Method currentUserM = activityManager.getDeclaredMethod("getCurrentUser");
            int userId = (int) currentUserM.invoke(null, (Object[]) null);
            LogUtils.d(TAG, "currentUid:" + userId);

            Class<?> userHandleC = Class.forName("android.os.UserHandle");
            Method ofM = userHandleC.getDeclaredMethod("of", int.class);
            UserHandle userHandle = (UserHandle) ofM.invoke(null, userId);
            LogUtils.d(TAG, "userHandle:" + userHandle);
            return userHandle;
        } catch (ClassNotFoundException | NoSuchMethodException |
                 InvocationTargetException | IllegalAccessException e) {
            LogUtils.d(TAG, "getCurrentUid error:" + e.getMessage());
        }
        return null;
    }


    @SuppressWarnings("deprecation")
    private static boolean isLauncherExist(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //获得task列表
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(20);
        if (taskInfo == null || taskInfo.isEmpty()) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo runningTaskInfo : taskInfo) {
            if (Objects.equals(ComponentName.unflattenFromString(LAUNCHER_COMPONENT),
                    runningTaskInfo.topActivity)) {
                return true;
            }
        }
        return false;
    }

    public static void openBtSettings(Context context) {
        Intent intent = new Intent("android.settings.BLUETOOTH_SETTINGS");
        intent.setPackage("ecarx.settings");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        doStartActivityAsUser(context, intent, true);
    }

    public static void openWifiSettings(Context context) {
        Intent intent = new Intent("android.settings.WIFI_SETTINGS");
        intent.setPackage("ecarx.settings");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        doStartActivityAsUser(context, intent, true);
    }

    public static void openHotspotSettings(Context context) {
        Intent intent = new Intent("android.settings.WIFI_SETTINGS");
        intent.setPackage("ecarx.settings");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        doStartActivityAsUser(context, intent, true);
    }

    public static void showToast(@StringRes int strId) {
        Toast.makeText(PluginContext.getContextByActThread(), PluginContext.getInstance().getPluginContext().getString(strId), Toast.LENGTH_SHORT).show();
    }
}
